package com.scribbles.user.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.scribbles.admin.dao.RoleDAO;
import com.scribbles.common.entity.AppRole;
import com.scribbles.common.entity.AppUser;
import com.scribbles.common.exception.ScribblesRuntimeException;
import com.scribbles.user.dao.UserDAO;
import com.scribbles.user.util.UserEnum;

@Service
public class UserService {

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private RoleDAO roleDAO;

	@Transactional
	public void createUser(AppUser appUser) {
		AppRole endUserRole = roleDAO.getReference(UserEnum.END_USER.getUserType());
		List<AppRole> appRoles = new ArrayList<AppRole>();
		appRoles.add(endUserRole);
		appUser.setRoles(appRoles);
		
		appUser.setCreatedBy(appUser.getCreatedBy());
		appUser.setCreatedDate(new Date());
		appUser.setUpdatedBy(appUser.getUpdatedBy());
		appUser.setUpdatedDate(new Date());
		userDAO.create(appUser);
		throw new ScribblesRuntimeException("Some problem in creating user");
	}	

	public List<AppUser> retrieveUsers() {
		return userDAO.findAll();
	}

	@Transactional
	public void removeUser(Integer id) {
		userDAO.remove(userDAO.getReference(id));
	}
	
	public AppUser getUser(int userId) { 
		return userDAO.findByPrimaryKey(userId);
	}
	
	@Transactional
	public void updateUser(AppUser appUser) {
		AppUser appUserManaged = userDAO.findByPrimaryKey(appUser.getId());
		appUserManaged.setFirstName(appUser.getFirstName());
		appUserManaged.setLastName(appUser.getLastName());
		appUserManaged.setDob(appUser.getDob());
		appUserManaged.setPassword(appUser.getPassword());
		appUserManaged.setUserId(appUser.getUserId());
		appUserManaged.setSex(appUser.getSex());
		appUserManaged.setEmailId(appUser.getEmailId());
		appUserManaged.setUpdatedBy(appUser.getCreatedBy());
		appUserManaged.setUpdatedDate(new Date());
		throw new ScribblesRuntimeException("Some problem in creating user");
	}

/*	public AppUser loadUserByUserId(String userId, String password) {
		AppUser appUser = null;
		appUser = userDAO.findByUserIdAndPassword(userId, password);
		return appUser;
	}

	public AppUser loadUserByUserId(String userId) {
		AppUser appUser = null;
		appUser = userDAO.findByUserId(userId);
		return appUser;
	}*/
}
